package ua.com.globallogic.training.subway;

import java.util.Date;

public class Turnstile {

    public boolean isCardInRegistry(Registry registry, long idToCheck){
        boolean result = false;
        for (SubwayCard card : registry.getEmittedCards()) {
            if (card.getId() == idToCheck) {
                result = true;
                System.out.println("Card is registered");
                break;
            } else {
                System.out.println("Card was not found in the registry");
            }
        }
        return result;
    }

    public boolean isCardPayable(SubwayCard card) {
        boolean result = false;
        if (card instanceof TimeBoundCard) {
            result = isTimeBoundCardPayable((TimeBoundCard)card);
        } else if (card instanceof TripsBoundCard) {
            result = isTripsBoundCardPayable((TripsBoundCard)card);
        } else if (card instanceof AccumulativeCard) {
            result = isAccumulativeCardPayable((AccumulativeCard)card);
        }
        return result;
    }

    private boolean isAccumulativeCardPayable(AccumulativeCard card) {
        return card.getBalance() >= Registry.FARE;
    }

    private boolean isTripsBoundCardPayable(TripsBoundCard card) {
        return card.getTripsCount() > 0;
    }

    private boolean isTimeBoundCardPayable(TimeBoundCard card) {
        Date currentDate = new Date();
        return !(card.getExpirationDate().after(currentDate));
    }

    public boolean performEntryCheck(SubwayCard card, Registry registry) {
        if (isCardInRegistry(registry, card.getId()) && isCardPayable(card)) {
            chargeOneTrip(card);
            System.out.println("Card accepted. Gates are open");
           // registry.addStatisticsEntry(card, true);
            return true;
        } else {
            System.out.println("Invalid card. Closing gates");
           // registry.addStatisticsEntry(card, false);
            return false;
        }
    }

    private void chargeOneTrip(SubwayCard card) {
        card.chargeOneTrip();
    }

}
